import json
import numpy as np
import os

# 读取 JSON 文件
def load_json(path):
    with open(path, 'r', encoding='utf-8') as f:
        return json.load(f)

# 计算模糊综合评价的结果向量
def fuzzy_evaluate(sample, W1, W2, R):
    # 构造每个一级指标的隶属度向量（按 R 二级指标合并）
    R_fused = {}
    for k1, w1 in W1.items():
        second_level = W2[k1]
        # 合并当前一级指标的隶属度向量
        fused = np.zeros(5)
        # 获取当前样本在该一级指标下的二级指标
        k2 = sample.get(k1)
        if k2 not in R:
            R_fused[k1] = fused
            continue
        r_vec = np.array([R[k2].get(str(i), 0.0) for i in range(1, 6)])
        w2_val = W2[k1].get(k2, 0.0)
        fused += w2_val * r_vec
        R_fused[k1] = fused

    # 一级指标加权合成
    final_vec = np.zeros(5)
    for k1, w1 in W1.items():
        final_vec += w1 * R_fused[k1]

    return final_vec

# 决策函数（最大隶属度法）
def risk_level(result_vec):
    idx = int(np.argmax(result_vec)) + 1
    mapping = {1: "低", 2: "较低", 3: "中等", 4: "较高", 5: "高"}
    return idx, mapping[idx]

if __name__ == "__main__":
    # 假设数据放在项目根目录下的 data 文件夹
    # 获取项目根目录（假设当前文件在项目子目录下）
    project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    data_dir = os.path.join(project_root, "数据")
    # 读取 3 个 JSON 文件
    W1 = load_json(os.path.join(data_dir, "一级指标权重.json"))
    W2 = load_json(os.path.join(data_dir, "二级指标权重.json"))
    R = load_json(os.path.join(data_dir, "模糊打分概率矩阵.json"))
    pipeline_data = load_json(os.path.join(data_dir, "管道数据.json"))

    sample = pipeline_data[0]

    result_vec = fuzzy_evaluate(sample, W1, W2, R)
    level_idx, level_name = risk_level(result_vec)

    print("输入样本数据：", sample)
    print("模糊综合评价结果向量：", result_vec.round(4).tolist())
    print(f"评估风险等级为：{level_idx}（{level_name}）")